package com.xiaoma.netty.server;

import com.xiaoma.provider.ServiceProvider;
import com.xiaoma.provider.ServiceProviderImpl;
import com.xiaoma.registry.NacosServiceRegistry;
import com.xiaoma.registry.ServiceRegistry;
import com.xiaoma.server.RpcServer;
import com.xiaoma.utils.CommonDecoder;
import com.xiaoma.utils.CommonEncoder;
import com.xiaoma.utils.JsonSerializer;
import com.xiaoma.utils.ShutdownHook;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;

/**
 * @Author: xiaoma
 * @Date: 2021/7/5 15:35
 * @description: netty方式服务提供侧服务端
 */
public class NettyServer implements RpcServer {

    private static final Logger logger = LoggerFactory.getLogger(NettyServer.class);

    private final String host;
    private final int port;
    private final ServiceRegistry serviceRegistry;
    private final ServiceProvider serviceProvider;

    public NettyServer(String host, int port) {
        this.host = host;
        this.port = port;
        serviceRegistry = new NacosServiceRegistry();
        serviceProvider = new ServiceProviderImpl();
    }

    @Override
    public <T> void publishService(T service, Class<T> serviceClass) {
        serviceProvider.addServiceProvider(service, serviceClass);
        serviceRegistry.register(serviceClass.getCanonicalName(), new InetSocketAddress(host, port));
        start();
    }
    @Override
    public void start() {
        //处理连接事件线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //处理IO读写事件线程组 默认为2*处理器线程数
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            //服务端启动助手
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            //设置启动助手的主从线程组
            serverBootstrap.group(bossGroup, workerGroup)
                     //设置通道为NIO
                    .channel(NioServerSocketChannel.class)
                     //以info日志级别打印出服务端日志
                    .handler(new LoggingHandler(LogLevel.INFO))
                     //bossGroup 连接等待个数
                    .option(ChannelOption.SO_BACKLOG, 256)
                     //设置心跳机制
                    .option(ChannelOption.SO_KEEPALIVE, true)
                     //关闭Nagle算法
                     //Nagle算法:为了减少发送包的次数,将很多小的数据包合成一个大数据包发送,但这回导致延迟发送,禁用该算法,保证实时性
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    //创建一个通道初始化对象
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            //通道处理链
                            ChannelPipeline pipeline = ch.pipeline();
                            //编码器
                            pipeline.addLast(new CommonEncoder(new JsonSerializer()));
                            //解码器
                            pipeline.addLast(new CommonDecoder());
                            //实际处理器
                            pipeline.addLast(new NettyServerHandler());
                        }
                    });
            ChannelFuture future = serverBootstrap.bind(host,port).sync();
            //注册钩子函数
            ShutdownHook.getShutdownHook().addClearAllHook();
            //对关闭通道进行监听
            future.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            logger.error("启动服务器时有错误发生: ", e);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

}
